﻿using System; using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KeanuMvc.Reference;
using HIS.Utils;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HISModels.Entities;
using System.Configuration;
using HIS.Utils.Securities;


namespace HIS.Controllers.Master {
    public class Banks : HIS.Controllers.AppBaseController {

        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private HISModels.Entities.Bank bank = null;
        private HISModels.Entities.Address bankaddress = null;
        private StringReader stringReader = null;
        #endregion

        #region Constructors


        public Banks() {
            Data.Add("Pagetitle", "Banks");
            Data.Add("Notification", strNotification);
        }

        #endregion

        [Authorization(RoleAction = "master-bank")]
        public override void Index() {
            try {
                Data["Pagetitle"] += " :: Bank List";
                RenderFile("Master\\Bank\\banklist.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "master-bank")]
        public void TableBankList() {


            try {
                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];
                string bankname = HttpContext.Current.Request["bankname"];
                string swiftcode = HttpContext.Current.Request["swiftcode"];


                string ssearch = "bankname=" + bankname + ";swiftcode=" + swiftcode;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = ssearch;

                string strUri = Global.ServiceUriDictionary["bankpaging"] + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                ///Convert to JObject
                ///  
                JObject o = JObject.Parse(stringReader.ReadToEnd());
                JArray aaData = (JArray)o["aaData"];
                ///Modify it
                JArray aaDataModified = new JArray();
                for (int i = 0; i < aaData.Count(); i++) {
                    JObject oo = JObject.Parse(aaData[i].ToString());
                    oo["Id"] = KeanuMvc.Reference.CryptoString.Encrypt(oo["Id"].ToString());
                    oo["NameValue"] = (oo["NameValue"]).ToString().ToUpper();
                    oo["SwiftCode"] = (oo["SwiftCode"]).ToString();
                    aaDataModified.Add(oo);

                }
                o["aaData"] = aaDataModified;

                ///So serialize
                strJson = JsonConvert.SerializeObject(o);

                HttpContext.Current.Response.Write(strJson);

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            } finally {
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-bank")]
        public void EditBank() {
            int id = 0;

            try {
                id = Convert.ToInt32(KeanuMvc.Reference.CryptoString.Decrypt(HttpContext.Current.Request["id"].ToString()));
            } catch {
                return;
            }

            try {
                string strUri = Global.ServiceUriDictionary["bank"] + id + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.GetJson(strUri);
                bank = JsonConvert.DeserializeObject<Bank>(stringReader.ReadToEnd());
                Data["Pagetitle"] += " :: Edit Bank";
                Data.Add("bank", bank);
                Data.Add("AddressDesc", bank.Addresses.FirstOrDefault().AddressDesc);
                Data.Add("AddressId", bank.Addresses.FirstOrDefault().Id);
                Data.Add("id", id);

                Data.Add("IsCreate", "false");
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Master\\Bank\\editbank.html");
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-bank")]
        public void DeleteBank() {
            int id = 0;
            try {
                id = int.Parse(KeanuMvc.Reference.CryptoString.Decrypt(HttpContext.Current.Request["id"].ToString()));
            } catch {
                return;
            }
            try {
                string strUri = Global.ServiceUriDictionary["bank"] + Global.ServiceUriDictionary["requestformat"];
                StringReader strReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                bank = JsonConvert.DeserializeObject<Bank>(strReader.ReadToEnd());

                if (bank != null) {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                } else {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }
                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                HttpContext.Current.Response.Write(strNotification);
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-bank")]
        public void Save() {
            StringReader stringReader = null;
            string strUri = string.Empty;
            int id = 0;

            if (HttpContext.Current.Request["IsCreate"] != "true") {
                try {
                    id = Convert.ToInt32(HttpContext.Current.Request["id"]);
                } catch { }

            }
            try {
                bank = new Bank();
                Utils.Helper.SetNullToEmptyString(bank);

                bank = new Bank() { NameValue = null, SwiftCode = null };
                bankaddress = new Address() { AddressDesc = null ,BankId = 0,Id=0};
                if (HttpContext.Current.Request.Form.Count > 0) {
                    ///(Get all request and set it to object with one condition, please ask your friend first!) All variable on view must be same as object property.
                    if (strNotification == string.Empty) {
                        bank.PostHandler<HISModels.Entities.Bank>();
                        bankaddress.PostHandler<HISModels.Entities.Address>();
                        
                        bankaddress.TypeId = 1;
                        bankaddress.Id = Convert.ToInt32(HttpContext.Current.Request["AddressId"]);
                        bankaddress.BankId = Convert.ToInt32(HttpContext.Current.Request["id"]);
                        bank.Addresses.Add(bankaddress);

                        if (HttpContext.Current.Request["IsCreate"] == "true") {
                            strUri = Global.ServiceUriDictionary["bank"] + Global.ServiceUriDictionary["requestformat"];
                            stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(bank));
                        } else {
                            strUri = Global.ServiceUriDictionary["bank"] + Global.ServiceUriDictionary["requestformat"];
                            stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(bank));
                        }
                        bank = JsonConvert.DeserializeObject<Bank>(stringReader.ReadToEnd());

                        if (bank != null) {
                            strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        } else {
                            strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        }
                        strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                    }
                }
            } catch (Exception ex) {
                strNotification = ex.Message;
            } finally {
                HttpContext.Current.Response.Write(strNotification);
            }
        }

        [Authorization(RoleAction = "master-bank")]
        public void AddBank() {
            try {
                Data["Pagetitle"] += " :: Create Bank";
                bank = new HISModels.Entities.Bank() { NameValue = string.Empty, SwiftCode = string.Empty, RecordStatus = 0 };
                bankaddress = new HISModels.Entities.Address() { AddressDesc = string.Empty, Id = 0 };
                Data.Add("bank", bank);
                Data.Add("AddressDesc", string.Empty);
                Data.Add("AddressId", Convert.ToInt32(HttpContext.Current.Request["AddressId"]).NullSafeToString());
                Data.Add("IsCreate", "true");
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Master\\Bank\\editbank.html");
                base.RestService.Dispose();
            }
        }



    }
}